"""
基金收益排行
http://fund.eastmoney.com
"""
import time
import random
import requests
from config import config
from time_out import timelimited


@timelimited(15)
def get_url(type, period, top_num):
    """

    :param type: 'gp', 'zs', 'qdii', 'hh'
    :param period: 'y', '3y', '6y', '1n'
    :param top_num:
    :return:
    """
    sleep_time = random.randint(a=1, b=8)
    # print('begin sleep: {}'.format(sleep_time))
    time.sleep(sleep_time)
    parameter = {
        'ft': type,
        'sc': period,
        'st': 'desc',
        'pi': 1,
        'pn': top_num,
        'cp': '',
        'ct': '',
        'cd': '',
        'ms': '',
        'fr': '',
        'plevel': '',
        'fst': '',
        'ftype': '',
        'fr1': '',
        'fl': 0,
        'isab': 1
    }

    req = requests.get(url=config.url, params=parameter, headers=config.header)
    if req and req.status_code == 200:
        return req.text

    return None


def parse_html(html):
    """

    :param html:
    :return:
    """
    html = html[html.index('[') + 1: html.index(']')]
    html = html.replace('"', '')
    arr = [data.split('|') for data in html.split(',')]
    return [data[0] for data in arr if len(data) >= 20]


def get_type_info(type, peroid_list, top_num=10):
    """

    :param type:
    :param peroid_list:
    :param top_num:
    :return:
    """
    code = set()
    for num, period in enumerate(peroid_list):
        try:
            html = get_url(type=type, period=period, top_num=top_num)
            if html:
                codes = parse_html(html=html)
                if num == 0:
                    code = set(codes)
                else:
                    if len(codes) == 0 or len(code) == 0:
                        return None
                    else:
                        code = code & set(codes)
        except Exception as e:
            print('reqest url error: {}'.format(e))

    return list(code) if code else None


def eastmoney_run(type, peroid_list, top_num):
    """

    :param type:
    :param peroid_list:
    :param top_num:
    :return:
    """
    code = get_type_info(type=type, peroid_list=peroid_list, top_num=top_num)
    return '；\t'.join(code) if code else '没有找到符合条件的基金'
